/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.dataset.firewall;

import nfse.NetFSE;
import nfse.NetFSERecord;
import nfse.NetFSEUtil;
import nfse.gui.record.FlexRecord;
import nfse.gui.record.FlexRecordField;

import java.util.StringTokenizer;

public class IPTablesRecord extends NetFSERecord {

    public int proto = -1;

    public int dstPort = -1;

    public int srcPort = -1;

    public long dstIP = -1;

    public String dstAddr = "";

    public String physicalInterfaceIn = "";

    public String physicalInterfaceOut = "";

    public String interfaceIn = "";

    public String interfaceOut = "";

    public String prec = "";

    public int ttl = -1;

    public String tos = "";

    public String id = "";

    public String action = "";

    public IPTablesRecord() {

    }
    
    public static void main(String[] args) {
        IPTablesRecord rec = new IPTablesRecord();
        rec.parse(args, rec);
    }

    public int[] getIndexedFields() {
        int[] temp = { NetFSE.FIELD_START_TS, NetFSE.FIELD_SRC_IP, NetFSE.FIELD_DST_IP, NetFSE.FIELD_DST_PORT };
        return temp;
    }

    public long getDstIP() {
        return dstIP;
    }

    public int getDstPort() {
        return dstPort;
    }

    public void setDstIP(long dstIP) {
        this.dstIP = dstIP;
        this.dstAddr = NetFSEUtil.convertLongToIP(dstIP);
    }

    public IPTablesRecord(int sensor) {
        this.setSensorID(sensor);
    }

    public NetFSERecord generate(String line, int sensor) throws Exception {

        // Record of the form: ts;srcip;May 29 09:17:11 hs62-logger IN=br0
        // OUT=br0
        // PHYSIN=eth0 PHYSOUT=eth1 SRC=146.138.87.221 DST=146.138.199.110
        // LEN=78 TOS=0x00 PREC=0x00 TTL=128 ID=79 PROTO=UDP SPT=137 DPT=137
        // LEN=58
        IPTablesRecord rec = new IPTablesRecord(sensor);

        rec.setInitialString(line);
        rec.setStartTS(NetFSEUtil.timestampFromSyslog(line));
        rec.setSrcIP(-1);
        rec.dstIP = -1;

        StringTokenizer st = new StringTokenizer(line);

        String token = st.nextToken();
        while (!token.endsWith(":")) { // Advance to the end of the header
            try {
                token = st.nextToken();
            } catch (java.util.NoSuchElementException e) {
                return null;
            }
        }

        while (st.hasMoreTokens()) {
            token = st.nextToken();
            String[] tokens2 = token.split("=");
            if (token.indexOf("=") == -1) {
                rec.action += token + " ";
            } else if (tokens2.length == 2) {
                if (tokens2[0].equals("SRC")) {
                    rec.setSrcAddr(tokens2[1]);
                    rec.setSrcIP(NetFSEUtil.convertIPtoLong(rec.getSrcAddr()));
                } else if (tokens2[0].equals("DST")) {
                    rec.dstAddr = tokens2[1];
                    rec.dstIP = NetFSEUtil.convertIPtoLong(rec.dstAddr);
                } else if (tokens2[0].equals("PREC")) {
                    rec.prec = tokens2[1];
                } else if (tokens2[0].equals("TTL")) {
                    rec.ttl = Integer.parseInt(tokens2[1]);
                } else if (tokens2[0].equals("TOS")) {
                    rec.tos = tokens2[1];
                } else if (tokens2[0].equals("ID")) {
                    rec.id = tokens2[1];
                } else if (tokens2[0].equals("PROTO")) {
                    rec.proto = NetFSEUtil.getProtocolValue(tokens2[1]);
                } else if (tokens2[0].equals("SPT")) {
                    rec.srcPort = Integer.parseInt(tokens2[1]);
                } else if (tokens2[0].equals("DPT")) {
                    rec.dstPort = Integer.parseInt(tokens2[1]);
                } else if (tokens2[0].equals("IN")) {
                    rec.interfaceIn = tokens2[1];
                } else if (tokens2[0].equals("OUT")) {
                    rec.interfaceOut = tokens2[1];
                } else if (tokens2[0].equals("PHYSIN")) {
                    rec.physicalInterfaceIn = tokens2[1];
                } else if (tokens2[0].equals("PHYSOUT")) {
                    rec.physicalInterfaceOut = tokens2[1];
                }
            }
        }
        rec.action = rec.action.trim();
        if (rec.action.endsWith(":"))
            rec.action = rec.action.substring(0, rec.action.length() - 2);
        if (rec.getSrcIP() == -1 || rec.dstIP == -1)
            return null;
        return rec;

    }

    public String getCreateFieldTableSQL(String table) {
        StringBuffer temp = new StringBuffer("create table " + table + " (ID bigint, ");
        temp.append("srcip inet,");
        temp.append("srcport int,");
        temp.append("dstip inet,");
        temp.append("dstport int,");
        temp.append("proto int,");
        temp.append("ethin varchar(50),");
        temp.append("ethout varchar(50),");
        temp.append("physin varchar(50),");
        temp.append("physout varchar(50),");
        temp.append("ttl int,");
        temp.append("tos varchar(10),");
        temp.append("action varchar(50),");
        temp.append("startts timestamp");
        temp.append(")");
        return temp.toString();
    }

    public FlexRecord getFlexRecord() {
        FlexRecord temp = new FlexRecord();
        temp.values = new String[13];
        int idx = -1;
        temp.values[++idx] = this.getTimestamp().toString();
        temp.values[++idx] = this.action + "";
        temp.values[++idx] = this.getSrcAddr();
        if (srcPort == -1)
            temp.values[++idx] = "";
        else
            temp.values[++idx] = this.srcPort + "";
        temp.values[++idx] = this.dstAddr;
        if (dstPort == -1)
            temp.values[++idx] = "";
        else
            temp.values[++idx] = this.dstPort + "";
        temp.values[++idx] = this.proto + "";
        temp.values[++idx] = this.interfaceIn + "";
        temp.values[++idx] = this.interfaceOut + "";
        temp.values[++idx] = this.physicalInterfaceIn + "";
        temp.values[++idx] = this.physicalInterfaceOut + "";
        temp.values[++idx] = this.ttl + "";
        temp.values[++idx] = this.tos + "";
        return temp;
    }

    public FlexRecordField[] getFlexRecordFields() {
        FlexRecordField[] temp = new FlexRecordField[13];
        int idx = -1;
        temp[++idx] = new FlexRecordField("Timestamp", "startts", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_TIMESTAMP);
        temp[++idx] = new FlexRecordField("Action", "action", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("Src IP", "srcip", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_IP_ADDR);
        temp[++idx] = new FlexRecordField("Src Port", "srcport", FlexRecordField.TYPE_INT,
                FlexRecordField.SUB_TYPE_PORT);
        temp[++idx] = new FlexRecordField("Dst IP", "dstip", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_IP_ADDR);
        temp[++idx] = new FlexRecordField("Dst Port", "dstport", FlexRecordField.TYPE_INT,
                FlexRecordField.SUB_TYPE_PORT);
        temp[++idx] = new FlexRecordField("Protocol", "proto", FlexRecordField.TYPE_INT,
                FlexRecordField.SUB_TYPE_PROTOCOL);
        temp[++idx] = new FlexRecordField("In", "ethin", FlexRecordField.TYPE_STRING, FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("Out", "ethout", FlexRecordField.TYPE_STRING, FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("Phys In", "physin", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("Phys Out", "physout", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("TTL", "ttl", FlexRecordField.TYPE_INT, FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("TOS", "tos", FlexRecordField.TYPE_STRING, FlexRecordField.SUB_TYPE_NONE);
        return temp;
    }

    public String getInsertFieldTableSQL(int id, String table) {
        StringBuffer temp = new StringBuffer("insert into " + table + " values (" + id + "");
        temp.append(",'");
        temp.append(getSrcAddr() + "'");
        temp.append(",");
        temp.append(srcPort + "");
        temp.append(",'");
        temp.append(dstAddr + "'");
        temp.append(",");
        temp.append(dstPort);
        temp.append(",");
        temp.append(proto);
        temp.append(",");
        temp.append("'" + interfaceIn + "'");
        temp.append(",");
        temp.append("'" + interfaceOut + "'");
        temp.append(",");
        temp.append("'" + physicalInterfaceIn + "'");
        temp.append(",");
        temp.append("'" + physicalInterfaceOut + "'");
        temp.append(",");
        temp.append("" + ttl + "");
        temp.append(",");
        temp.append("'" + tos + "'");
        temp.append(",");
        temp.append("'" + action + "'");
        temp.append(",");
        temp.append("'" + getTimestamp().toString() + "'");
        temp.append(")");
        return temp.toString();
    }

    public boolean isSyslog() {
        return true;
    }

}